#include "players.h"
#include "units.h"
#include "gui.h"



player::player( int i, string n, PlayerType t )
{
	id = i;
	name = n;
	typ = t;
	time = parameters::get_instance()->game_parameters[ "START_TIME" ];
	in_game = true;
};



player::~player()
{
	for( unsigned int i = 0; i < units.size(); ++i )
	{
		delete units[ i ];
	}
	units.clear();
};



player* player::clone()
{
	player* p = new player( id, name, typ );
	p->set_time( time );
	for( unsigned int i = 0; i < units.size(); ++i )
	{
		unit* cu = dynamic_cast< unit* >( units[ i ]->clone() );
		cu->set_player( p );
		p->units.push_back( cu );
	}
	p->ai_algorithm = ai_algorithm;
	return p;
};



bool player::buy_unit( unit* u, unsigned int x, unsigned int y )
{
	pre_buy_info* pbi = new pre_buy_info( u, x, y );
	if ( ( int )u->get_price() > this->get_time() )
		return false;
	if ( dynamic_cast< object* >( mapa::get_instance()->get_object( x, y ) ) != 0 )
		return false;
	if ( mapa::get_instance()->terrain->get( x, y ) >= 20000 )
		return false;
	if ( units.size() >= parameters::get_instance()->game_parameters[ "MAX_UNITS" ] )
		return false;
	if ( mapa::get_instance()->terrain->get( x, y ) % 10 == id )
		return false;
	unit* nu = dynamic_cast< unit* >( u->clone() );
	units.push_back( nu );
	nu->init( x, y, this, ( units.size() + 1 ) );
	mapa::get_instance()->set_object( nu, x, y );
	this->set_time( get_time() - nu->get_price() );
	game_gui::get_instance()->show_buy( nu, x, y, pbi );
	return true;
};



bool player::sell_unit( unsigned int n )
{
	if ( n >= units.size() )
		return false;
	vector< unit* >::iterator it = units.begin() + n;
	unit* u = *it;
	pre_sell_info* psi = new pre_sell_info( u );
	mapa::get_instance()->set_object( 0, u->get_x(), u->get_y() );
	this->set_time( get_time() + u->get_price() );
	delete u;
	units.erase( units.begin() + n );
	game_gui::get_instance()->show_sell( 0, psi );
	return true;
};